/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    Text,
    useTheme,
    Container,
    Button,
    IconArrowRight,
    Input,
    Select,
    CheckSwitch,
    LineColumn,
    SuffixInput, InputLine, ComboBoxDatalist, InputDatalist,
    CommitInput, TextArea, ButtonRefComp
} from "customize-easy-ui-component";
//import { DialogEnterReturn } from "../../context/DialogEnterReturn";
//import queryString from "querystring";
// import {useCommnBaseParm, CommnBase} from "./CommnBase";
import {useContext, useRef} from "react";
import {ChooseEqps} from "../../comp/ChooseEqps";
import useFlowToMutation from "../hook/useFlowRequestMutation";
import {OneUserChoose} from "../../common/user/OneUserChoose";
import RoutingContext from "../../routing/RoutingContext";
import {使用状态s} from "../../pipeline/edit/管道单元";
import UserContext from "../../routing/UserContext";
import {ChooseUnit} from "../../unit/ChooseUnit";
import {Link as RouterLink} from "../../routing/Link";
// import HashLinkObserver from "react-hash-link";

// export const 设备单位关联类型s=[['useu','使用单位'],['owner','产权单位'],['mtu','维保单位']];

interface Props {
  // id?: string;
  readOnly?: boolean;
  editable?: boolean;
  //当前申请单数据
  req?:any;
  //去修改设备数据
  //setEqp:  React.Dispatch<React.SetStateAction<any>>;
  //graphQL的变更执行回调函数 (...args: any[]) => any
  mutationFunc: (...args: any[]) => any;
  //当前待办流转单
    curFlow?:any;
}
/** 报告书修订执行申请单。
 * */
export const RevisionExecution: React.FunctionComponent<Props> = (
    {
       readOnly,
       editable,
       req=null,    //【只读的】:从好几代祖先前的DetailedGuide在graphQL获得后端服务器数据层层传递下来的。
      mutationFunc,
        curFlow,
     }) =>
{
  //这个位置就应该体现解析graphQL内省的json集合字段：data:{}从string变身对象。
  const theme = useTheme();
    const { history } = useContext(RoutingContext);
  const {save, field, reurl}= window.history.state?.state??{};      //通用伪对话框传递格式:多选设备返回对象
    //假如从多选选定设备页面返回的："移出多选集" : "加入多选集" 操作过后，将会导致save.devs[]对象变身成了设备页面的经过SessionStorage倒腾一手的对象。
  const edt = save?  save : req;
  //若从save恢复的，confirm已经解析为对象Object:
  const  dat = edt?.dat instanceof Object?  edt?.dat : JSON.parse(edt?.dat || '{}');
  const [理由, set理由] = React.useState(dat?.理由);
    const [repNO, setRepNO] = React.useState(dat?.repNO);
    const [rpURL, setRpURL] = React.useState(dat?.rpURL);
  //【琢磨】仅仅存在于短期流程活动使用的需要结构化吗？成本和收益对比？,本来应当是关联对象的却被非结构化，graphQL没办法内省的，片段快照某些关键字段？？
    //非结构化关联对象的和正常JPA关联对象的优缺点对照： 前者适合于频繁新增删除的，关系生存时间短暂的，后端基本不参与计算的。
    //因为ChooseEqps对话框选择设备之后返回的实际数据字段通常是save.devs而不是我这非结构化json存储到了dat:{devs{[]}}，所以需要转换 #前提条件save?.devs表示挑选设备列表伪对话框之后调回来的。
    const [devs, setDevs] = React.useState(save?.devs? save.devs : dat?.devs);
    // const [unitZd, setUnitZd] = React.useState(dat?.unitZd || 'useu');
    //因为servu为对方框原本预计并非是在dat{servu:{}}这个结构里面的# 只好这样转换了 save? save.devs : 多个为对话框的混淆逻辑问题 【预设不应该有dat{}非结构化】
    //注意@前提：假定save.servu必须时选择了单位从伪对话框返回的。
    // const [servu, setServu] = React.useState(save?.servu? save.servu : dat?.servu);
    const [ust, setUst] = React.useState(dat?.ust);

  async function confirmation() {
    //前面垫底加了newdat={ ...req,  导致；id字段在XxxInput并没有定义，报错！输入和输出模型不能交换。
    const newdat={
      dat: {
          理由, repNO, rpURL
        },
    };
    //伪对话框跳转恢复也会用到的。
    return newdat;
  }
  //console.log("ChooseUnit跑来8history=",history, "location==",history.location);
/* const mountedRef = useRef(false);
  if(!mountedRef.current) {
    console.log("电梯Z组件当前id=",id,"未初始化￥=",mountedRef.current);
    mountedRef.current = true;
  }
  else   console.log("电梯Z组件当前id=",id,"已经初始化了=",mountedRef.current);*/

  // console.log("电梯组件传递x参数来svp Nowneqp=",req, "save=",save, cbp);

    const {call:flowToFunc,doing:flowing, called:flowed, reset:flowreset}=useFlowToMutation();
    //流转可能遇见两个人物：auditor审核人 或者 dispatcher最终责任人
    const [auditor, setAuditor] = React.useState<any>(req?.auditor);
    const [director, setDirector] = React.useState<any>(req?.director);
    const [manager, setManager] = React.useState<any>(req?.manager);
    const {user} = useContext(UserContext);
    const  audat = JSON.parse(edt?.audat || '{}');
    const [memo, setMemo] = React.useState<string|undefined>(audat?.memo);
    const  drdat = JSON.parse(edt?.drdat || '{}');
    //本组件有可能没有remount的就无法根据relay读取的数据来完全同同步更新。强制刷新页面代价较大的，考虑其它做法：？？
    const [drmemo, setDrmemo] = React.useState<string|undefined>(drdat?.memo);
    const  mndat = JSON.parse(edt?.mndat || '{}');
    const [mnmemo, setMnmemo] = React.useState<string|undefined>(mndat?.memo);
    const floUrl='/request/'+ req?.id;
    const commitBlurRef =React.useRef(null);

    const 未尽事s= 理由?.split(/\r?\n/) || [];

  return (
    <div
      css={{
        [theme.mediaQueries.md]: {
          height: "auto",
          display: "block"
        }
      }}
    >
      <Text
        css={{
          flex: 1,
          textAlign: "center",
          [theme.mediaQueries.md]: {
            textAlign: "left"
          }
        }}
        wrap={true}
        variant="h5"
        gutter={false}
      >
        本检验机构报告维护部门(信息中心)主管审批、后台维护人员接受申请并执行一共2关
      </Text>

      <div
        css={{
          flex: 1,
          [theme.mediaQueries.md]: {
            flex: "none"
          }
        }}
      >
        <div>
          <Container>
            <div
              css={{
                paddingTop: theme.spaces.lg,
                paddingBottom: theme.spaces.lg
              }}
            >
                <Text variant="h6">第一步，申请资料:</Text>
                <LineColumn >

                  <InputLine label={`本检验机构报告号:`}>
                      {
                          (req?.status==='INIT') ?
                              <CommitInput  value={ repNO || ''}  onSave={txt => setRepNO( txt || undefined) } />
                              :
                              <Text css={{textAlign: "left"}}>{repNO}</Text>
                      }
                  </InputLine>
                    <InputLine label={`申请报告书修订许可单:`}>
                        <div>
                            {
                             (req?.status==='INIT') &&
                                <CommitInput placeholder={'从申请报告书修订申请单复制来的链接'} value={ rpURL || ''}  onSave={txt => setRpURL( txt || undefined) } />
                            }
                            <RouterLink href={`${rpURL}`} css={{display: 'flex'}}>
                             看关联"申请报告书修订"申请单
                            </RouterLink>
                        </div>
                    </InputLine>
                    <InputLine label={`许可后追加说明:`}>
                        {
                            (req?.status==='INIT') ?
                                <TextArea required rows={9}
                                          value={理由} onChange={e => set理由( e.currentTarget.value||undefined ) }
                                />
                                :
                                <div>
                                    {
                                        未尽事s.map((rule: string,i:number) => (
                                            <Text key={i} css={{
                                                // textIndent: '2rem',
                                                display: 'flex',
                                                textAlign: "left"
                                            }}>
                                                {rule}
                                            </Text>
                                        ))
                                    }
                                </div>
                        }
                    </InputLine>

                 </LineColumn>

                {
                    (req?.status==='INIT') &&
                      <Button size="lg" intent="primary"  iconAfter={<IconArrowRight />}
                              css={{ marginTop: theme.spaces.sm, whiteSpace:'unset' }}
                              disabled={req?.status !== 'INIT'}
                        onPress={ async () => {
                          const sendInp=await confirmation();
                          const inpPreare={ ...sendInp,
                              dat: JSON.stringify({...sendInp.dat}),
                          };
                          await mutationFunc(req?.id, 'UPD', inpPreare);
                        } }
                      > 先保存申请资料
                      </Button>
                }
            </div>

              <InputLine label='报告维护部门主管:'>
                  { req?.status==='INIT' ?
                      <OneUserChoose name={manager?.person?.name!} setEditorVar={setManager}
                                     oobj={manager}/>
                      :
                      <Text css={{textAlign: "left"}}>{manager?.person?.name}</Text>
                  }
              </InputLine>
              { (req?.status==='INIT' || (curFlow && curFlow?.entId === req?.id && curFlow?.tdId==='request_author_modify') ) &&
                  <Button intent="primary" disabled={(curFlow && !(curFlow?.entId === req?.id) && req?.status!=='INIT') || !manager}
                          onPress={async () => {
                              await flowToFunc(curFlow?.utId, req?.id,2,"", "YES","报告书修订执行:"+user?.person?.name,
                                  manager?.id, floUrl, 40);
                              sessionStorage['审批单'] = null;
                              history.push(`/zeebeTodo`);
                          }}
                  >
                      { ((curFlow?.tdId==='request_author_modify')? '再提交申请' : '提交申请给审核人') }
                  </Button>
              }

              <Text variant="h6">第二步，报告维护部门信息中心主管审核情况：</Text>
{/*              <InputLine  label='用报告编号查' >
                  <Input  value={mnmemo || ''}  placeholder="那一份报告？"
                          onChange={e => setMnmemo(e.currentTarget.value) } />
              </InputLine>*/}
              <InputLine label={`放行意见:`}>
                  { curFlow?.tdId==='request_manager_opinion' ?
                      <CommitInput  value={ mnmemo || ''}  onSave={txt => setMnmemo( txt || undefined) }
                                    placeholder="如果拒绝或回退的，请给出理由"
                      />
                      :
                      <Text css={{textAlign: "left"}}>{mndat?.memo || ' '}</Text>
                  }
              </InputLine>
              <InputLine label='后台维护人员:'>
                  { curFlow?.tdId==='request_manager_opinion' ?
                      <OneUserChoose name={auditor?.person?.name!} setEditorVar={setAuditor}
                                     oobj={auditor}/>
                      :
                      <Text css={{textAlign: "left"}}>{auditor?.person?.name}</Text>
                  }
              </InputLine>

              { (curFlow?.entId === req?.id && curFlow?.tdId==='request_manager_opinion') &&
                  <>
                  <ButtonRefComp intent="primary" disabled={(curFlow && !(curFlow?.entId === req?.id))  || !auditor}
                                 ref={commitBlurRef}  onPointerOver={(e :any) => { // @ts-ignore
                                    commitBlurRef!.current!.focus(); }}
                          onPress={ async() => {
                              if(!mnmemo || ""===mnmemo)    throw new Error(`请输入意见mnmemo=${mnmemo}`);
                              //<CommitInput 地输入可能来不及收集触发： onBlur? onEnter()导致了 opndat为空parse JSON: unable to decode JSON: EOF：似乎async更好捕获mnmemo
                              const opndat= req?.status==='INIT' ? '' :
                                                JSON.stringify({memo:mnmemo,});
                             await flowToFunc(curFlow?.utId, req?.id,1,opndat, "YES","报告书修订执行:"+user?.person?.name,
                                  auditor?.id, null, 20);
                              sessionStorage['审批单'] = null;     //后端这时流程节点可能已运行到了下一个节点了。
                              history.push(`/zeebeTodo`);
                          }}
                  >
                      {'通过的流转下步给后台维护人员'}
                  </ButtonRefComp>
                  {
                      (req?.status!=='INIT') &&
                      <>
                          <Button intent="primary" css={{marginLeft: theme.spaces.sm}}
                                  disabled={curFlow && !(curFlow?.entId === req?.id)}
                                  onPress={async () => {
                                      const opndat=JSON.stringify({memo:mnmemo,});
                                      await flowToFunc(curFlow?.utId, req?.id,1,opndat, "NO","报告书修订执行:"+user?.person?.name,
                                          null, null, 30);
                                      sessionStorage['审批单'] = null;
                                      history.push(`/zeebeTodo`);
                                  }}
                          >
                              { '审批不通过' }
                          </Button>
                          <Button intent="primary" css={{marginLeft: theme.spaces.sm}}
                                  disabled={curFlow && !(curFlow?.entId === req?.id)}
                                  onPress={async () => {
                                      const opndat=JSON.stringify({memo:mnmemo,});
                                      await flowToFunc(curFlow?.utId, req?.id,1,opndat, "BACK","报告书修订执行:"+user?.person?.name,
                                          null, null, 30);
                                      sessionStorage['审批单'] = null;
                                      history.push(`/zeebeTodo`);
                                  }}
                          >
                              { '退回' }
                          </Button>
                      </>
                  }
               </>
            }
            

              <Text variant="h6">第三步，后台维护人员接受并处理：</Text>
              {  ((curFlow && curFlow?.entId === req?.id) || req?.status!=='INIT') &&
                  <InputLine label={`修订完成情况:`}>
                      {
                          (curFlow?.entId === req?.id && curFlow?.tdId==='request_auditor_opinion') ?
                              <CommitInput  value={ memo || ''}  onSave={txt => setMemo( txt || undefined) }
                                            placeholder="如果拒绝或回退的，请给出理由"
                              />
                              :
                              <Text css={{textAlign: "left"}}>{memo}</Text>
                      }
                  </InputLine>
              }

              { (curFlow?.entId === req?.id && curFlow?.tdId==='request_auditor_opinion') &&
                  <>
                      <Button intent="primary" disabled={curFlow && !(curFlow?.entId === req?.id)}
                              onPress={async () => {
                                  const opndat= req?.status==='INIT' ? '' :
                                      JSON.stringify({memo,});

                                  await flowToFunc(curFlow?.utId, req?.id,2,opndat, "YES","报告书修订执行:"+user?.person?.name,
                                      null, null, 40);
                                  sessionStorage['审批单'] = null;
                                  history.push(`/zeebeTodo`);
                              }}
                      >
                          { '已经想办法修改且修改后的报告也上线' }
                      </Button>
                      {
                          (req?.status!=='INIT') &&
                          <>
                              <Button intent="primary" css={{marginLeft: theme.spaces.sm}}
                                      disabled={curFlow && !(curFlow?.entId === req?.id)}
                                      onPress={async () => {
                                          const opndat=JSON.stringify({memo,});
                                          await flowToFunc(curFlow?.utId, req?.id,2,opndat, "NO","报告书修订执行:"+user?.person?.name,
                                              null, null, 30);
                                          sessionStorage['审批单'] = null;
                                          history.push(`/zeebeTodo`);     //实际并不会等待后端的响应的，直接跳转URL的。# await flowToFunc并不会阻塞到应答
                                      }}
                              >
                                  { '拒绝修改报告' }
                              </Button>
                              <Button intent="primary" css={{marginLeft: theme.spaces.sm}}
                                      disabled={curFlow && !(curFlow?.entId === req?.id)}
                                      onPress={async () => {
                                          const opndat=JSON.stringify({memo,});
                                          await flowToFunc(curFlow?.utId, req?.id,2,opndat, "BACK","报告书修订执行:"+user?.person?.name,
                                              null, null, 30);
                                          //为何点一次：后端跑了2回？？ 而且接口没保存memo?
                                          sessionStorage['审批单'] = null;
                                          history.push(`/zeebeTodo`);     //实际并不会等待后端的响应的，直接跳转URL的。# await flowToFunc并不会阻塞到应答
                                      }}
                              >
                                  { '退回' }
                              </Button>
                          </>
                      }
                  </>
              }


            { (curFlow?.entId === req?.id && (curFlow?.tdId==='request_deny' || curFlow?.tdId==='request_finish')) &&
                <>
              <Button intent="primary" disabled={curFlow && !(curFlow?.entId === req?.id)}
                      onPress={async () => {
                          await flowToFunc(curFlow?.utId, req?.id,1,'', "YES");
                          sessionStorage['审批单'] = null;
                          history.push(`/zeebeTodo`);
                      }}
              >
                {curFlow?.tdId==='request_finish'? '报告修改完确认' : '晓得了'}
              </Button>
              { curFlow?.tdId==='request_finish' &&
                  <Text>有问题可找维护人员理论</Text>
              }
                </>
            }


          </Container>
        </div>
      </div>

    </div>
  );
};


